package com.nazca.tvremote.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.nazca.tvremote.util.RLog;

public class RemoteSender {

	private static final String TAG = "EventSender";
	
	private Socket mSocket;
	private PrintWriter mPrintWriter;
	
	private String mDstAddress;
	private int mDstPort;
	
	private boolean mIsConnecting = false;
	
	public RemoteSender(String dstAddress, int dstPort){
		RLog.d(TAG, "RemoteSender()");
		mDstAddress = dstAddress;
		mDstPort = dstPort;
		mSocket = new Socket();
	}
	
	public void println(String str){
//		RLog.d(TAG, "println()");
		if(connect()){
//			RLog.d(TAG, "if(connect())");
//			RLog.d(TAG, "out begin");
			if(mPrintWriter != null){
				mPrintWriter.println(str);
			}
//			RLog.d(TAG, "out end");
		}
	}
	
	public boolean close(){
		RLog.d(TAG, "close()");
		if(mSocket != null){
			try {
				mSocket.shutdownOutput();
				mSocket.close();
				mSocket = null;
				return true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public boolean connect(){
//		RLog.d(TAG, "connect()");
//		RLog.d(TAG, "mIsConnecting:"+mIsConnecting);
		if(mIsConnecting){
			return false;
		}
		try {
			if (mSocket == null || !mSocket.isConnected() /*|| mSocket.isClosed() || mSocket.isOutputShutdown()*/) {
//			    RLog.d(TAG, "if (!mSocket.isConnected())");
			    mIsConnecting = true;
				mSocket.connect(new InetSocketAddress(mDstAddress, mDstPort));
				mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
				mSocket.setKeepAlive(true);
				mIsConnecting = false;
			}
			return true;
		}catch (IOException e) {
			e.printStackTrace();
		} 
		return false;
	}
}
